<template>
  <div class="app-container">
    <es-header title="购物车案例"></es-header>

    <div class="main">
      <es-goods
        v-for="item in goodsList"
        :key="item.id"
        :id="item.id"
        :thumb="item.goods_img"
        :count="item.goods_count"
        :price="item.goods_price"
        :title="item.goods_name"
        :checked="item.goods_state"
        @stateChange="onGoodsStateChange"
        @countChange="onGoodsCountChange"
      ></es-goods>
    </div>

    <es-footer
      @fullChange="onFullStateChange"
      :amount="amount"
      :total="total"
    ></es-footer>
  </div>
</template>

<script>
import EsHeader from '../components/shoppingCar/EsHeader.vue';
import EsFooter from '../components/shoppingCar/EsFooter.vue';
import EsGoods from '../components/shoppingCar/EsGoods.vue';
import { getCurrentInstance } from 'vue';

export default {
  name: 'Car',
  components: {
    EsHeader,
    EsFooter,
    EsGoods,
  },
  data() {
    return {
      // 商品列表的数据
      goodsList: [],
    };
  },
  // 组件实例创建完毕之后的生命周期函数
  created() {
    // 调用methods中的getGoodsList方法，请求商品列表数据
    this.getGoodsList();
  },
  methods: {
    // 获取商品列表数据的方法
    async getGoodsList() {
      const currentInstance = getCurrentInstance();
      const { $http } = currentInstance.appContext.config.globalProperties;
      let res = await $http.get('/api/cart');
      if (res.status !== 200) return alert('数据请求失败');
      this.goodsList = res.data.list;
    },

    // 监听选中状态
    // 监听商品变化的事件
    onGoodsStateChange(value) {
      console.log(value); //{}
      this.goodsList.some((item) => {
        if (item.id === value.id) {
          item.goods_state = value.ischecked;
          return true; // ?
        }
      });
    },

    // 监听是否全选
    onFullStateChange(isFull) {
      this.goodsList.forEach((item) => (item.goods_state = isFull));
    },

    // 监听数量变化
    onGoodsCountChange(value) {
      console.log(value); //{}
      this.goodsList.forEach((item) => {
        if (item.id == value.id) {
          item.goods_count = value.num;
        }
      });
    },
  },
  computed: {
    // 已勾选商品的总价格
    amount() {
      let sum = 0;
      this.goodsList
        .filter((item) => item.goods_state === true)
        .forEach((item) => {
          sum += item.goods_price * item.goods_count;
        });
      return sum;
    },
    //  已勾选商品的总数量
    total() {
      let sum = 0;
      this.goodsList
        .filter((item) => item.goods_state === true)
        .forEach((item) => {
          sum += item.goods_count;
        });
      return sum;
    },
  },
};
</script>

<style scoped>
.main {
  margin-bottom: 40px;
}
</style>
